package cn.com.oceansoft.modules.matters.controller;

import cn.com.oceansoft.application.Constant;
import cn.com.oceansoft.application.constant.ConfigInfo;
import cn.com.oceansoft.application.common.base64.Base64;
import cn.com.oceansoft.application.common.util.HttpClientUtil;
import cn.com.oceansoft.framework.kits.ApiResult;
import cn.com.oceansoft.modules.base.entity.ApiQueryBase;
import cn.com.oceansoft.modules.cache.service.BaseCacheService;
import cn.com.oceansoft.modules.matters.entity.MattersQuery;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 * Created by huqp on 01/10/2016.
 */
@Controller
@RequestMapping("matters")
public class MattersController {

    @Resource
    protected ConfigInfo configInfo;

    @Resource
    private BaseCacheService cacheService;

    /**
     * 事项中心首页
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "index", method = GET)
    public String gotoMattersIndex(HttpServletRequest request) {
        return "matters/mattersCenter";
    }

    /**
     * 事项分类
     *
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "case-catalog", method = GET)
    private Object getCaseCatalog(@RequestParam("type") String type) {
        String url = "";
        if (type.equals("JZ")) {
            url = "/matters/pccs";
        } else if (type.equals("GR")) {
            url = "/matters/groups?typeid=P";
        } else if (type.equals("QY")) {
            url = "/matters/groups?typeid=B";
        }

        String result = cacheService.get("ue:case:catalog" + type);
        if (StringUtils.isBlank(result)) {
            result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + url);
            cacheService.setHour("ue:case:catalog" + type, result, 24);
        }
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    /**
     * 事项列表
     *
     * @param mattersQuery
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "case-list", method = POST)
    private Object getCaseList(MattersQuery mattersQuery) {

        if(StringUtils.isNotBlank(mattersQuery.getKw())){
            mattersQuery.setKw(mattersQuery.getKw().replace(" ",""));
        }
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/page",
                "ps", mattersQuery.getPs(), "pi", mattersQuery.getPi(), "typeId", mattersQuery.getTypeId(), "kw", mattersQuery.getKw());
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;

    }

    /**
     * 获取办事指南
     *
     * @param caseGuid
     * @return
     */
    @RequestMapping(value = "detail/{caseGuid}", method = GET)
    public String loadMattersDetail(@PathVariable("caseGuid") String caseGuid, Model model, HttpServletRequest request) throws IOException {

        String result = cacheService.get("ue:case:detail:" + caseGuid);
        if (StringUtils.isBlank(result)) {
            result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/" + caseGuid);
        }

        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        if (null != apiResult && null != apiResult.getData() && StringUtils.isNotBlank(apiResult.getData().toString()) && !"[]".equals(apiResult.getData().toString())) {
            cacheService.setHour("ue:case:detail:" + caseGuid, result, 24);
        }

        //通知公告
        String noticeResult = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/news/gsgg",
                "ps", 5, "pi", 1, "kw", "");
        ApiResult noticeApiResult = JSONObject.parseObject(noticeResult, ApiResult.class);
        //警务资讯
        String newResult = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/news/page",
                "ps", 5, "pi", 1, "kw", "jwzx");
        ApiResult newApiResult = JSONObject.parseObject(newResult, ApiResult.class);

        model.addAttribute("caseGuide", apiResult.getData());
        model.addAttribute("caseGuid", caseGuid);
        model.addAttribute("noticeList", noticeApiResult.getData());
        model.addAttribute("newList", newApiResult.getData());

        return "matters/mattersDetail";
    }

    /**
     * 样表预览
     *
     * @param guid
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "case-manifest", method = GET)
    private Object getCaseManifest(@RequestParam("guid") String guid, @RequestParam("type") String type) {

        String result = cacheService.get("ue:case:manifest" + guid + type);
        if (StringUtils.isBlank(result)) {
            result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/manifests/" + guid, "type", type);
            cacheService.setHour("ue:case:manifest" + guid + type, result, 24);
        }
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    /**
     * 下载表格
     *
     * @param guid
     * @param type
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "ajax-download-check", method = GET)
    public Object ajaxDownloadCheck(@RequestParam("guid") String guid, @RequestParam("type") String type, HttpServletResponse response) throws IOException {

        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/manifests/" + guid, "type", type);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);

        if (apiResult.getData() != null) {
            return new ApiResult(true, 10200, "", null);
        } else {
            return new ApiResult(false, 10001, "资源不存在，请联系系统管理员", null);
        }

    }

    /**
     * 下载表格
     *
     * @param guid
     * @param type
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "ajax-download", method = GET)
    public void ajaxDownload(@RequestParam("guid") String guid, @RequestParam("type") String type, HttpServletResponse response) throws IOException {

        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/manifests/" + guid, "type", type);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        JSONObject jsonObject = JSONObject.parseObject(apiResult.getData().toString());
        String suffix = jsonObject.get("mime").toString().replace(".","");
        String fileContent = jsonObject.get("fileContent").toString();
        String filename = UUID.randomUUID().toString().replace("-", "") + "." +suffix;
        try {

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.decode(fileContent.getBytes("UTF-8")));
            response.setContentType("applicatoin/octet-stream");
            response.setContentLength(Integer.valueOf(byteArrayInputStream.available()));
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            OutputStream outputStream = response.getOutputStream();
            IOUtils.copy(byteArrayInputStream, outputStream);
            outputStream.close();
            outputStream.flush();
            byteArrayInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 表格下载主页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "form-index", method = GET)
    public String gotoFormsIndex(HttpServletRequest request, Model model) {
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/dicPcc");
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        model.addAttribute("pcc", apiResult.getData());
        return "matters/forms-index";
    }

    /**
     * 表格下载列表页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "form-list", method = POST)
    public String gotoFormsList(HttpServletRequest request, ApiQueryBase query, Model model) {

        System.out.println("aa");
        //获取列表
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/form-list",
                "ps", query.getPs(), "pi", query.getPi(), "kw", query.getKw());
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        System.out.println(apiResult);
        model.addAttribute("result", apiResult);
        //return apiResult;
        return "matters/forms-list";
    }


    /**
     * 跳转到事项申报页面
     *
     * @return
     */
    @RequestMapping(value = "apply", method = GET)
    public String gotoApplyIndex(@RequestParam(value = "caseGuid", required = true) String caseGuid, Model model, HttpServletRequest request) {
        try {
            // 事项详情
            String result = cacheService.get("ue:case:detail:" + caseGuid);
            if (StringUtils.isBlank(result)) {
                result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/" + caseGuid);
            }

            ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
            Object apiResultData = apiResult.getData();
            if (null != apiResult && null != apiResultData && StringUtils.isNotBlank(apiResultData.toString()) && !"[]".equals(apiResultData.toString())) {
                cacheService.setHour("ue:case:detail:" + caseGuid, result, 24);
            }

            // 第一级机构
            Object firstDepts = this.getDept((String) ((JSONObject) apiResultData).get("matNum"),
                    configInfo.getMattersFirstDeptId(), configInfo.getMattersDeptLev()).getData();

            //通知公告
            String noticeResult = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/news/gsgg",
                    "ps", 5, "pi", 1, "kw", "");
            ApiResult noticeApiResult = JSONObject.parseObject(noticeResult, ApiResult.class);

            //警务资讯
            String newResult = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/news/page",
                    "ps", 5, "pi", 1, "kw", "jwzx");
            ApiResult newApiResult = JSONObject.parseObject(newResult, ApiResult.class);

            // 申请人信息
//            Map<String,String> user = (Map)request.getSession().getAttribute(Constant.CURRENT_MEMBER);
//            String accountId = user.get("accountId");
//            String applyUser = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/members/account/"+accountId);
//            String applyUser = HttpClientUtil.doGet("http://192.168.1.16:8083/osc/members/account/13999999999");
//            ApiResult applyUserResult = JSONObject.parseObject(applyUser, ApiResult.class);

            model.addAttribute("caseDetail", apiResultData);
            model.addAttribute("firstDepts", firstDepts);
            model.addAttribute("noticeList", noticeApiResult.getData());
            model.addAttribute("newList", newApiResult.getData());
            model.addAttribute("applyUser", request.getSession().getAttribute(Constant.CURRENT_MEMBER));

            model.addAttribute("attAddUrl", configInfo.getMsHostUrl() + "/tasks/att");//附件上传地址
            model.addAttribute("applyProjectUrl", configInfo.getMsHostUrl() + "/tasks");//申报地址
        } catch (Exception e) {
            e.printStackTrace();// 日志
            throw new RuntimeException(e.getMessage());
        }
        return "matters/mattersApply";
    }

    /**
     * 事项申报
     *
     * @return
     */
    @RequestMapping(value = "apply", method = POST)
    public String ApplyMatters() {

        return "matters/mattersApply";
    }

    /**
     * 获取事项申报部门列表(受理公安机关)
     *
     * @param matNum 事项编号
     * @param deptId 上级部门ID
     * @param lev    等级，下一级=上一级+13
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "ajax-mattersDept", method = GET)
    public Object getMattersDept(@RequestParam("matNum") String matNum,
                                 @RequestParam("deptId") String deptId,
                                 @RequestParam("lev") String lev) {

        return getDept(matNum, deptId, lev).getData();
    }

    /**
     * 获取事项申报部门列表(受理公安机关)
     *
     * @param matNum 事项编号
     * @param deptId 上级部门ID
     * @param lev    等级
     * @return
     */
    private ApiResult getDept(String matNum, String deptId, String lev) {
        lev = Strings.isNullOrEmpty(lev) ? configInfo.getMattersDeptLev() : lev;
        String result = null;
        result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/depts", "matNum", matNum, "deptId", deptId, "lev", lev);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    /**
     * TODO 附件上传，返回保存成功后的guid
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "ajax-att", method = POST)
    public ApiResult reportMattersAtt(MultipartHttpServletRequest request) {
        MultipartFile mp = request.getFile("materialFile");

        String fileName = mp.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);

        if(!suffix.toUpperCase().equals("JPG")
                && !suffix.toUpperCase().equals("PNG")
                && !suffix.toUpperCase().equals("DOC")
                && !suffix.toUpperCase().equals("DOCX")
                && !suffix.toUpperCase().equals("XLSX")
                && !suffix.toUpperCase().equals("XLS")){
            return ApiResult.failure(0,"图片格式不正确！");
        }
        if(mp.getSize() < 10*1024){
            return ApiResult.failure(0,"附件大小小于10K！");
        }

        if(mp.getSize() > 500*1024){
            return ApiResult.failure(0,"附件大小超过500K！");
        }

        File file = new File(new Date().getTime() + "");
        try {
            FileUtils.writeByteArrayToFile(file, mp.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = HttpClientUtil.uploadFile(configInfo.getMsHostUrl() + "/tasks/att", file);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        file.delete();
        JSONObject json = new JSONObject();
        json.put("fileName", mp.getOriginalFilename());
        json.put("guid", apiResult.getData());
        return ApiResult.succ(json);
    }

    @ResponseBody
    @RequestMapping(value = "ajax-att/{guid}", method = DELETE)
    public ApiResult deleteMattersAtt(@PathVariable String guid, HttpServletRequest request) {
        String result = null;

        result = HttpClientUtil.doDel(configInfo.getMsHostUrl() + "/tasks/att/" + guid);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    /**
     * TODO 申报
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "ajax-project", method = POST)
    public ApiResult prjApp(HttpServletRequest request, @RequestBody Map map) {

//        String deptId = request.getParameter("deptId");
//        String matNum = request.getParameter("matNum");
//        String accountId = request.getParameter("accountId");
//
//        String linkAddress = request.getParameter("linkAddress");
//        String linkPhone = request.getParameter("linkPhone");
//
//        String manifests = request.getParameter("manifests");
//
//        String netProjectType = request.getParameter("netProjectType");
//        String tskSource = request.getParameter("tskSource");
//
//        String str = "{'deptId:'" + deptId
//                +  ",'matNum:'" + matNum
//                +  ",'accountId:'" + accountId
//                +  ",'linkAddress:'" + linkAddress
//                +  ",'manifests:'" + manifests
//                +  ",'linkPhone:'" + linkPhone
//                +  ",'netProjectType:'" + netProjectType
//                +  ",'tskSource:'" + tskSource
//                +"}";
//        System.out.println(str);
        System.out.println(JSON.toJSONString(map));
        String result = HttpClientUtil.doPostString(configInfo.getMsHostUrl() + "/tasks", map);

        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    @RequestMapping(value = "pccs", method = RequestMethod.GET)
    @ResponseBody
    public Object findPolicyTypes(HttpServletRequest request) {
        ApiResult apiResult = null;
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "matters/pccs");
        apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    @RequestMapping(value = "dicts/{key:.+}", method = RequestMethod.GET)
    @ResponseBody
    public Object findDicts(@PathVariable("key") String key, HttpServletRequest request) {
        ApiResult apiResult = null;
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "dicts/key/" + key);
        apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }
}
